package com.zhuizikejithreeig.cn.threeigkeji.loginfo;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.zhuizikejithreeig.cn.been.ForgNumberBeen;

import com.zhuizikejithreeig.cn.been.MacErrBeen;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.PasswordNameSave;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.MediaType;

public class ResetPasswordActivity extends BasicActivity implements View.OnClickListener {

    private static final int REGIST = 12;
    private EditText mName1;
    private EditText mName2;
    private Button mName8;
    private String mCodeRecover;
    private String mPhoneNumber;
    private boolean hasPermission = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_reset_password);


        setLeftShow(1, R.mipmap.back);
        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mName1 = findViewById(R.id.name1);
        mName2 = findViewById(R.id.name2);

        mCodeRecover = CompontApplayCation.loginRegistCode;
        mPhoneNumber = CompontApplayCation.loginRegistPhone;


        mName8 = findViewById(R.id.name8);
        mName8.setOnClickListener(this);
        if (mCodeRecover == null || mPhoneNumber == null) {
            finish();
        }
        hasPermission();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击完成
            case R.id.name8:

                if (hasPermission) {

                    if (isConnected()) {

                        regist();

                    } else {
                        ToastMake.showToast(getResources().getString(R.string.string57));
                    }
                } else {

                    hasPermission();
                    return;
                }
                break;
        }
    }


    private void regist() {

        final String passWord = mName1.getText().toString().trim();
        String passWordTwo = mName2.getText().toString().trim();

        if (TextUtils.isEmpty(passWord) || TextUtils.isEmpty(passWordTwo)) {
            ToastMake.showToast(getResources().getString(R.string.string53));
            return;
        }

        if (!Utils.everyPaw(passWord)) {
            return;
        }

        if (!TextUtils.equals(passWord, passWordTwo)) {
            ToastMake.showToast(getResources().getString(R.string.string39));
            return;
        }
        HashMap<String, String> map = new HashMap<>();

        map.put("phone", mPhoneNumber);
        map.put("pwd", passWord);
        map.put("code", mCodeRecover);
        String json = GsonUtil.parseMapToJson(map);

        showProgrees(getResources().getString(R.string.string41));
        OkHttpUtils
                .postString()
                .url(UriContect.PASSWORD)
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                        ToastMake.showToast(getResources().getString(R.string.string58));
                        hideProgree();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        ForgNumberBeen been = GsonUtil.parseJsonToBean(response, ForgNumberBeen.class);
                        MacErrBeen errBeen = GsonUtil.parseJsonToBean(response, MacErrBeen.class);
                        if (been == null) {
                            if (errBeen!=null){
                                ToastMake.showToast(errBeen.getMsg());
                            }
                            return;
                        }
                        if (!TextUtils.equals(been.getError_code(), "0")) {
                            ToastMake.showToast(been.getMsg());
                            return;
                        } else {
                         //   ToastMake.showToast(been.getMsg());
                            //保存账号跟密码
                            if (Utils.sdIsOk() && hasPermission) {
                                PasswordNameSave.savePassword(ResetPasswordActivity.this, mPhoneNumber, passWord, true);
                            } else {
                                ToastMake.showToast(getResources().getString(R.string.string43));
                            }
                            CompontApplayCation.loginNeedFinsh = true;
                            skipOtherActivity(LoginActivity.class, true);
                            //防止回退清空全部任务栈
//                            Intent intent = new Intent(ResetPasswordActivity.this, LoginActivity.class);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                            startActivity(intent);
                            finish();

                        }
                    }
                });
    }

    private void hasPermission() {
        PermissionGen.with(ResetPasswordActivity.this)
                .addRequestCode(REGIST)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = REGIST)
    public void requestPhotoSuccess() {
        //成功之后的处理
        //.......
        hasPermission = true;
    }

    @PermissionFail(requestCode = REGIST)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面
        hasPermission = false;

        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(ResetPasswordActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (showRequestPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //        Uri uri = Uri.fromParts("package", context.getPackageName());
            //        intent.setData(uri);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

    }

}
